<template>
	<div class="dashboard-wrap">
		<div class="clearfix pb-2">
			<a-space :size="20" class="float-left mt-2 flex-wrap">
				<a-select
					size="large"
					placeholder="请选择查询范围"
					v-model:value="searchForm.data"
					class="w-[200px]"
					@change="dataChange"
				>
					<a-select-option v-if="store.roleAuthMap.self" value="1">本人</a-select-option>
					<a-select-option v-if="store.roleAuthMap.dept" value="2">本部门</a-select-option>
					<a-select-option v-if="store.roleAuthMap.deptAndSub" value="3">本部门及下级部门</a-select-option>
					<a-select-option v-if="store.roleAuthMap.all" value="4">全企业</a-select-option>
					<a-select-option v-if="store.roleAuthMap.dept" value="5" @click="onCustomClick">自定义</a-select-option>
				</a-select>
				<a-tree-select
					v-if="searchForm.data === '5'"
					v-model:value="searchForm.tempPersonIds"
					size="large"
					style="width: 360px"
					:tree-data="orgUserTreeData"
					tree-checkable
					allow-clear
					:show-checked-strategy="SHOW_PARENT"
					placeholder="请选择人员范围"
					tree-node-filter-prop="label"
					:fieldNames="fieldNames"
					max-tag-count="responsive"
					:dropdownMatchSelectWidth="false"
					treeNodeFilterProp="name"
					@change="onPersonChange"
				/>
				<a-select
					size="large"
					placeholder="请选择查询范围"
					v-model:value="searchForm.day"
					class="w-[200px]"
					@change="timeChange"
				>
					<a-select-option value="0">今天</a-select-option>
					<a-select-option value="2">本周</a-select-option>
					<a-select-option value="4">本月</a-select-option>
					<a-select-option value="6">自定义</a-select-option>
				</a-select>
				<a-range-picker
					v-if="searchForm.day === '6'"
					size="large"
					style="width: 400px"
					v-model:value="selfTime"
					:disabledDate="disabledDate"
					format="YYYY-MM-DD"
					valueFormat="YYYY-MM-DD"
					@change="dateRangeChange"
					@calendarChange="onCalendarChange"
				/>
				<a-button type="primary" shape="round" @click="reset">重置</a-button>
			</a-space>
			<a-space v-if="nowDateTime" class="float-right mt-4 ml-3">
				<span class="updateTime">更新时间：{{ nowDateTime }}</span>
				<SyncOutlined class="text-[20px] pl-[5px] pr-[15px] cursor-pointer" @click="init" />
			</a-space>
		</div>

		<a-spin :spinning="onLoading" size="large" style="min-height: 70vh">
			<!-- 销售简报 -->
			<div class="mt-[12px] mb-[20px]">
				<div class="section-title">销售简报</div>
				<a-card :loading="onLoading" class="rounded-[12px]" :bodyStyle="{ padding: '40px 0' }">
					<div class="flex justify-around">
						<div class="flex-1 flex flex-col gap-[36px]" style="padding: 5px 0">
							<div class="flex justify-center">
								<div class="flex-[2]"></div>
								<div class="flex-[3] text-left">
									<div class="sale-title">领取企业</div>
									<div class="sale-value">
										{{ sketchVo.recevieCompanyNum ?? '' }}
									</div>
								</div>
								<div class="flex-[2]"></div>
								<div class="flex-[3] text-left">
									<div class="sale-title">{{ dayShowTip }}</div>
									<div class="flex items-center gap-1">
										<template v-if="!diyDateStatus">
											<img
												v-if="sketchVo.recevieCompanyRadio && Number(sketchVo.recevieCompanyRadio) > 0"
												src="@/assets/dashboardicons/uparow.png"
												class="trend-icon"
											/>
											<img
												v-if="sketchVo.recevieCompanyRadio && Number(sketchVo.recevieCompanyRadio) < 0"
												src="@/assets/dashboardicons/downarow.png"
												class="trend-icon"
											/>
											<span class="sale-prop">{{ Math.abs(Number(sketchVo.recevieCompanyRadio)) }}%</span>
										</template>
										<span v-else class="sale-prop">---</span>
									</div>
								</div>
								<div class="flex-[2]"></div>
							</div>
							<div class="flex justify-center">
								<div class="flex-[2]"></div>
								<div class="flex-[3] text-left">
									<div class="sale-title">新增跟进</div>
									<div class="sale-value">
										{{ sketchVo.addFollowNum ?? '' }}
									</div>
								</div>
								<div class="flex-[2]"></div>
								<div class="flex-[3] text-left">
									<div class="sale-title">{{ dayShowTip }}</div>
									<div class="flex items-center gap-1">
										<template v-if="!diyDateStatus">
											<img
												v-if="sketchVo.addFollowRadio && Number(sketchVo.addFollowRadio) > 0"
												src="@/assets/dashboardicons/uparow.png"
												class="trend-icon"
											/>
											<img
												v-if="sketchVo.addFollowRadio && Number(sketchVo.addFollowRadio) < 0"
												src="@/assets/dashboardicons/downarow.png"
												class="trend-icon"
											/>
											<span class="sale-prop">{{ Math.abs(Number(sketchVo.addFollowRadio)) }}%</span>
										</template>
										<span v-else class="sale-prop">---</span>
									</div>
								</div>
								<div class="flex-[2]"></div>
							</div>
						</div>
						<div class="border-2 border-r border-solid border-[#DDD]"></div>
						<div class="flex-1 flex flex-col gap-[36px]" style="padding: 5px 0">
							<div class="flex justify-center">
								<div class="flex-[2]"></div>
								<div class="flex-[3] text-left">
									<div class="sale-title">新增客户</div>
									<div class="sale-value">
										{{ sketchVo.addCustomerNum ?? '' }}
									</div>
								</div>
								<div class="flex-[2]"></div>
								<div class="flex-[3] text-left">
									<div class="sale-title">{{ dayShowTip }}</div>
									<div class="flex items-center gap-1">
										<template v-if="!diyDateStatus">
											<img
												v-if="sketchVo.addCustomerRadio && Number(sketchVo.addCustomerRadio) > 0"
												src="@/assets/dashboardicons/uparow.png"
												class="trend-icon"
											/>
											<img
												v-if="sketchVo.addCustomerRadio && Number(sketchVo.addCustomerRadio) < 0"
												src="@/assets/dashboardicons/downarow.png"
												class="trend-icon"
											/>
											<span class="sale-prop">{{ Math.abs(Number(sketchVo.addCustomerRadio)) }}%</span>
										</template>
										<span v-else class="sale-prop">---</span>
									</div>
								</div>
								<div class="flex-[2]"></div>
							</div>
							<div class="flex justify-center">
								<div class="flex-[2]"></div>
								<div class="flex-[3] text-left">
									<div class="sale-title">成交客户</div>
									<div class="sale-value">
										{{ sketchVo.turnoverNum ?? '' }}
									</div>
								</div>
								<div class="flex-[2]"></div>
								<div class="flex-[3] text-left">
									<div class="sale-title">{{ dayShowTip }}</div>
									<div class="flex items-center gap-1">
										<template v-if="!diyDateStatus">
											<img
												v-if="sketchVo.turnoverRadio && Number(sketchVo.turnoverRadio) > 0"
												src="@/assets/dashboardicons/uparow.png"
												class="trend-icon"
											/>
											<img
												v-if="sketchVo.turnoverRadio && Number(sketchVo.turnoverRadio) < 0"
												src="@/assets/dashboardicons/downarow.png"
												class="trend-icon"
											/>
											<span class="sale-prop">{{ Math.abs(Number(sketchVo.turnoverRadio)) }}%</span>
										</template>
										<span v-else class="sale-prop">---</span>
									</div>
								</div>
								<div class="flex-[2]"></div>
							</div>
						</div>
						<div class="border-2 border-r border-solid border-[#DDD]"></div>
						<div class="flex-1 flex flex-col gap-[36px]" style="padding: 5px 0">
							<div class="flex justify-center">
								<div class="flex-[2]"></div>
								<div class="flex-[3] text-left">
									<div class="sale-title">新增联系人</div>
									<div class="sale-value">
										{{ sketchVo.addContactsNum ?? '' }}
									</div>
								</div>
								<div class="flex-[2]"></div>
								<div class="flex-[3] text-left">
									<div class="sale-title">{{ dayShowTip }}</div>
									<div class="flex items-center gap-1">
										<template v-if="!diyDateStatus">
											<img
												v-if="sketchVo.addContactsRadio && Number(sketchVo.addContactsRadio) > 0"
												src="@/assets/dashboardicons/uparow.png"
												class="trend-icon"
											/>
											<img
												v-if="sketchVo.addContactsRadio && Number(sketchVo.addContactsRadio) < 0"
												src="@/assets/dashboardicons/downarow.png"
												class="trend-icon"
											/>
											<span class="sale-prop">{{ Math.abs(Number(sketchVo.addContactsRadio)) }}%</span>
										</template>
										<span v-else class="sale-prop">---</span>
									</div>
								</div>
								<div class="flex-[2]"></div>
							</div>
							<div class="flex justify-center">
								<div class="flex-[2]"></div>
								<div class="flex-[3] text-left">
									<div class="sale-title">合同金额</div>
									<div class="sale-value">
										{{ sketchVo.contractPirce ?? '' }}
									</div>
								</div>
								<div class="flex-[2]"></div>
								<div class="flex-[3] text-left">
									<div class="sale-title">{{ dayShowTip }}</div>
									<div class="flex items-center gap-1">
										<template v-if="!diyDateStatus">
											<img
												v-if="sketchVo.contractRadio && Number(sketchVo.contractRadio) > 0"
												src="@/assets/dashboardicons/uparow.png"
												class="trend-icon"
											/>
											<img
												v-if="sketchVo.contractRadio && Number(sketchVo.contractRadio) < 0"
												src="@/assets/dashboardicons/downarow.png"
												class="trend-icon"
											/>
											<span class="sale-prop">{{ Math.abs(Number(sketchVo.contractRadio)) }}%</span>
										</template>
										<span v-else class="sale-prop">---</span>
									</div>
								</div>
								<div class="flex-[2]"></div>
							</div>
						</div>
						<div class="border-2 border-r border-solid border-[#DDD]"></div>
						<div class="flex-1 flex justify-center" style="padding: 5px 0">
							<div class="flex-[2]"></div>
							<div class="flex-[3] text-left">
								<div class="sale-title">通话次数</div>
								<div class="sale-value">
									{{ sketchVo.callNum ?? '' }}
								</div>
							</div>
							<div class="flex-[2]"></div>
							<div class="flex-[3] text-left">
								<div class="sale-title">{{ dayShowTip }}</div>
								<div class="flex justify-left gap-1">
									<template v-if="!diyDateStatus">
										<img
											v-if="sketchVo.callRadio && Number(sketchVo.callRadio) > 0"
											src="@/assets/dashboardicons/uparow.png"
											class="trend-icon"
										/>
										<img
											v-if="sketchVo.callRadio && Number(sketchVo.callRadio) < 0"
											src="@/assets/dashboardicons/downarow.png"
											class="trend-icon"
										/>
										<span class="sale-prop">{{ Math.abs(Number(sketchVo.callRadio)) }}%</span>
									</template>
									<span v-else class="sale-prop">---</span>
								</div>
							</div>
							<div class="flex-[2]"></div>
						</div>
					</div>
				</a-card>
			</div>
			<!-- 销售助手 -->
			<div class="flex gap-[15px]">
				<div class="flex-1">
					<div class="section-title mt-[30px]">销售助手</div>
					<a-card :loading="onLoading" class="h-[320px] rounded-[12px]" :bodyStyle="{ padding: '44px 20px' }">
						<a-row class="leading-[36px]">
							<a-col :span="8">
								<div class="text-center mb-[40px]">
									<span class="helper-title">今日领取/分配的企业</span><br />
									<div class="helper-value">
										{{ salesHelper.recevieCompanyNum ?? '' }}
									</div>
								</div>
							</a-col>
							<a-col :span="8">
								<div class="text-center mb-[40px]">
									<span class="helper-title">今日将被回收的企业</span><br />
									<div class="helper-value">
										{{ salesHelper.recoveryCompanyNum ?? '' }}
									</div>
								</div>
							</a-col>
							<a-col :span="8">
								<div class="text-center mb-[40px]">
									<span class="helper-title">今日未联系的企业</span><br />
									<div class="helper-value">
										{{ salesHelper.linkNotCompanyNum ?? '' }}
									</div>
								</div>
							</a-col>
							<a-col :span="8">
								<div class="text-center">
									<span class="helper-title">今日领取/分配的客户</span><br />
									<div class="helper-value">
										{{ salesHelper.recevieCustomerNum ?? '' }}
									</div>
								</div>
							</a-col>
							<a-col :span="8">
								<div class="text-center">
									<span class="helper-title">今日将被回收的客户</span><br />
									<div class="helper-value">
										{{ salesHelper.recoveryCustomerNum ?? '' }}
									</div>
								</div>
							</a-col>
							<a-col :span="8">
								<div class="text-center">
									<span class="helper-title">今日未跟进的客户</span><br />
									<div class="helper-value">
										{{ salesHelper.linkNotCustomerNum ?? '' }}
									</div>
								</div>
							</a-col>
						</a-row>
					</a-card>
				</div>
				<!-- 合同金额 -->
				<div class="flex-1 max-w-[50%]">
					<div class="section-title mt-1">合同金额</div>
					<a-card :loading="onLoading" class="h-[320px] rounded-[12px]" :bodyStyle="{ padding: '12px' }">
						<div v-if="chartData.length === 0" class="flex items-center justify-center min-h-[350px]">
							<a-empty />
						</div>
						<div v-show="chartData.length" ref="useChartRef" />
					</a-card>
				</div>
			</div>
			<!-- 客户转化 -->
			<div class="flex gap-[15px] mt-[20px]">
				<div class="flex-1">
					<div class="flex justify-between items-center w-full">
						<div class="section-title mt-[30px]">客户转化</div>
						<a-select
							v-model:value="customerFromId"
							size="large"
							class="w-[240px] mt-[-15px]"
							:options="customerFromOptions"
							@change="onSourceChange"
						>
						</a-select>
					</div>
					<a-card :loading="onLoading" class="min-h-[360px] rounded-[12px]">
						<div class="relative ml-[100px] mr-[140px]">
							<div class="leading-[40px] mt-10">
								<div class="transfer-wrap flex items-center gap-3 bg-[var(--primary-color)] rounded-[14px] text-white">
									<img src="@/assets/dashboardicons/customer.png" class="transfer-icon" />
									<span class="flex-1 transfer-title">线索总数</span>
									<span class="transfer-value">{{ customerTrans.clueNum ?? '' }}</span>
								</div>
								<div class="transfer-wrap flex items-center gap-3 bg-[var(--primary-color)] rounded-[14px] text-white">
									<img src="@/assets/dashboardicons/customer.png" class="transfer-icon" />
									<span class="flex-1 transfer-title">客户总数</span>
									<span class="transfer-value">{{ customerTrans.number ?? '' }}</span>
								</div>
								<div class="transfer-wrap flex items-center gap-3 bg-[var(--primary-color)] rounded-[14px] text-white">
									<img src="@/assets/dashboardicons/sign.png" class="transfer-icon" />
									<span class="flex-1 transfer-title">合同签约的客户数</span>
									<span class="transfer-value">{{ customerTrans.contractnumber ?? '' }}</span>
								</div>
								<div
									class="clueToContract absolute left-[-40px] top-[26px] w-[40px] h-[152px] border-[2px] border-solid border-blue-400 border-r-0 rounded-tl-md rounded-bl-md"
								>
									<span class="absolute top-[63px] right-[60%] bg-white leading-[26px]">{{
										customerTrans.clueRatio || '0.00%'
									}}</span>
									<span
										class="absolute bottom-[-9px] right-[-9px] w-[0] h-[0] border-[8px] border-r-transparent border-t-transparent border-b-transparent border-solid border-blue-400"
									></span>
								</div>
								<div
									class="clueToCustomer absolute right-[-70px] top-[26px] w-[70px] h-[76px] border-[2px] border-solid border-blue-400 border-l-0 rounded-tr-md rounded-br-md"
								>
									<span class="absolute top-[25px] left-[80%] bg-white leading-[26px]">{{
										customerTrans.cluePersonRatio || '0.00%'
									}}</span>
									<span
										class="absolute bottom-[-9px] left-[-9px] w-[0] h-[0] border-[8px] border-l-transparent border-t-transparent border-b-transparent border-solid border-blue-400"
									></span>
								</div>
								<div
									class="customerToContract absolute right-[-40px] top-[100px] w-[40px] h-[76px] border-[2px] border-solid border-blue-400 border-l-0 border-t-0 rounded-tr-md rounded-br-md"
								>
									<span class="absolute top-[25px] left-[60%] bg-white leading-[26px]"
										>{{ customerTrans.ratio || '0.00' }}%</span
									>
									<span
										class="absolute bottom-[-9px] left-[-9px] w-[0] h-[0] border-[8px] border-l-transparent border-t-transparent border-b-transparent border-solid border-blue-400"
									></span>
								</div>
							</div>
						</div>
					</a-card>
				</div>
				<!-- 排行榜 -->
				<div class="flex-1">
					<div class="flex justify-between items-center">
						<div class="section-title mt-1">排行榜</div>
						<a-select v-model:value="rankType" size="large" class="w-[240px] mt-[-15px]" @change="onRankChange">
							<a-select-option value="0">新增合同金额</a-select-option>
							<a-select-option value="1">新增领取企业</a-select-option>
							<a-select-option value="2">新增客户</a-select-option>
						</a-select>
					</div>
					<a-card :loading="onLoading" class="min-h-[360px] rounded-[12px]">
						<div v-if="rankingList.length">
							<div
								v-if="rankType === '0'"
								class="flex justify-around rounded-[20px] px-[32px]"
								style="font-size: 16px; color: #333"
							>
								<span class="pl-2 rank-field">姓名</span>
								<span>成交金额</span>
								<span>落后金额</span>
							</div>
							<div
								v-else-if="rankType === '1'"
								class="flex justify-around rounded-[20px] px-[32px]"
								style="font-size: 16px; color: #333"
							>
								<span class="pl-2 rank-field">姓名</span>
								<span>领取企业</span>
								<span>落后数量</span>
							</div>
							<div
								v-else-if="rankType === '2'"
								class="flex justify-around rounded-[20px] px-[32px]"
								style="font-size: 16px; color: #333"
							>
								<span class="pl-2 rank-field">姓名</span>
								<span>新增客户</span>
								<span>落后数量</span>
							</div>

							<div
								v-for="(item, index) in rankingList"
								:key="index"
								class="flex justify-around rounded-[20px] mt-[18px] relative rank-wrap"
								:style="getColor(index)"
							>
								<div class="flex items-center">
									<img v-if="index === 0" src="@/assets/dashboardicons/one.png" class="absolute rank-icon" />
									<img v-if="index === 1" src="@/assets/dashboardicons/two.png" class="absolute rank-icon" />
									<img v-if="index === 2" src="@/assets/dashboardicons/three.png" class="absolute rank-icon" />
									<div v-if="index > 2" class="absolute rank-icon"></div>
									<span class="pl-2 rank-title">{{ item.personName }}</span>
								</div>
								<span class="rank-title">{{ item.price }} {{ getUnit }}</span>
								<div>
									<div v-if="[1, 2].includes(item.type)" class="flex items-center">
										<img v-if="item.type === 1" src="@/assets/dashboardicons/uparow.png" class="w-[17px]" />
										<img v-else-if="item.type === 2" src="@/assets/dashboardicons/downarow.png" class="w-[17px]" />
										<span class="pl-1 rank-title">{{ item.contrastPrice || 0 }} {{ getUnit }}</span>
									</div>
									<span v-else class="rank-title pl-[34px] pr-[20px]"> --- </span>
								</div>
							</div>
						</div>
						<div v-else class="flex items-center justify-center min-h-[300px]">
							<a-empty />
						</div>
					</a-card>
				</div>
			</div>
		</a-spin>
	</div>

	<!-- 自定义选择部门 -->
	<a-modal v-model:visible="selfChooseVisible" title="自定义选择部门" @ok="selfSearch">
		<div class="max-h-[400px] overflow-auto">
			<a-tree
				v-if="treeData.length > 0"
				v-model:selectedKeys="treeKeys"
				v-model:expandedKeys="defaultExpandedKeys"
				:tree-data="treeData"
				:field-names="treeFieldNames"
				@select="treeSelect"
			>
			</a-tree>
		</div>
	</a-modal>
	<!-- 销售报表弹窗 -->
	<sales-kit ref="salesKitRef"></sales-kit>
</template>
<script setup>
	import { isEmpty } from 'lodash-es'
	import orgApi from '@/api/biz/bizOrgApi'
	import SalesKit from './SalesKit.vue'
	import { Chart } from '@antv/g2'
	import customerSourceApi from '@/api/biz/crm/customerSourceApi'
	import dashboardApi from '@/api/biz/dashboardApi'
	import { message, TreeSelect } from 'ant-design-vue'
	import dayjs from 'dayjs'
	import { globalStore } from '@/store'
	import tool from '@/utils/tool'

	const store = globalStore()

	const nowDateTime = ref(null)

	/**
	 * ====================
	 *       基本逻辑
	 * ====================
	 */
	onMounted(async () => {
		await init()

		window.addEventListener('resize', () => {
			const timer = setTimeout(() => {
				nextTick(() => {
					clearTimeout(timer)
					drawUsageChart()
				})
			}, 800)
		})
	})

	const init = () => {
		if (searchForm.value.day === '6') {
			if (!selfTime.value || selfTime.value.length === 0) {
				message.warning('自定义请选择时间')
				return
			}
			searchForm.value.stime = selfTime.value[0]
			searchForm.value.etime = selfTime.value[1]
		}

		onLoading.value = true

		searchForm.value.dataStr = searchForm.value.personIds.join(',')
		Promise.all([getChartsData(), getSales(), getTankings(), getCustomerTrans()]).then((res) => {
			const [{ rmbVoList, sketchVo: sketchVoData }, salesHelperData, rankingListData, customerTransData] = res
			chartData.value = rmbVoList
			sketchVo.value = sketchVoData

			const e = document.createEvent('Event')
			e.initEvent('resize', true, true)
			window.dispatchEvent(e)

			salesHelper.value = salesHelperData
			rankingList.value = rankingListData
			customerTrans.value = customerTransData

			onLoading.value = false
			nowDateTime.value = dayjs().format('YYYY-MM-DD HH:mm:ss')

			nextTick(() => {
				drawUsageChart()
			})
		})
	}
	const onLoading = ref(true)
	const searchForm = ref({
		data: '1',
		dataStr: '',
		tempPersonIds: [],
		personIds: [],
		day: '4',
		stime: '',
		etime: ''
	})
	const dayShowTip = ref('较上月')
	const selfTime = ref([])
	const dates = ref([])
	const diyDateStatus = computed(() => searchForm.value.day === '6' && selfTime.value && selfTime.value.length)
	const onCalendarChange = (val) => {
		dates.value = val
	}
	const disabledDate = (current) => {
		if (!dates.value || dates.value.length === 0) {
			return false
		}
		const diffDate = current.diff(dates.value[0], 'days')
		return Math.abs(diffDate) > 30
	}
	const reset = () => {
		searchForm.value = {
			data: '1',
			dataStr: '',
			tempPersonIds: [],
			personIds: [],
			day: '4',
			stime: '',
			etime: ''
		}
		selfTime.value = []
		init()
	}

	/**
	 * ====================
	 *     自定义部门逻辑
	 * ====================
	 */
	const SHOW_PARENT = TreeSelect.SHOW_PARENT
	const fieldNames = {
		label: 'name',
		value: 'id'
	}
	const orgUserTreeData = ref(store.authDeptList)
	const onPersonChange = (value, label, extra) => {
		searchForm.value.personIds = tool.getAllBottomPersonIds(extra.allCheckedNodes)
		init()
	}

	const selfChooseVisible = ref(false)
	const treeData = ref([])
	const defaultExpandedKeys = ref([])
	const treeKeys = ref([])
	const treeFieldNames = { children: 'children', title: 'name', key: 'id' }
	const dataChange = (value) => {
		// if (searchForm.value.data === '5') {
		// 	orgApi.orgTree().then((res) => {
		// 		if (res !== null) {
		// 			treeData.value = res
		// 			if (isEmpty(defaultExpandedKeys.value)) {
		// 				// 默认展开2级
		// 				treeData.value.forEach((item) => {
		// 					// 因为0的顶级
		// 					if (item.parentId === '0') {
		// 						defaultExpandedKeys.value.push(item.id)
		// 						// 取到下级ID
		// 						if (item.children) {
		// 							item.children.forEach((items) => {
		// 								defaultExpandedKeys.value.push(items.id)
		// 							})
		// 						}
		// 					}
		// 				})
		// 			}
		// 		}
		// 		selfChooseVisible.value = true
		// 	})
		// }

		nextTick(() => {
			if (value !== '5') {
				onCustomClick()
				init()
			}
		})
	}
	const onCustomClick = () => {
		searchForm.value.tempPersonIds = []
		searchForm.value.personIds = []
	}

	const timeChange = (value) => {
		if (value === '6') {
			return
		}
		selfTime.value = []
		if (value === '0') {
			dayShowTip.value = '较昨天'
		} else if (value === '2') {
			dayShowTip.value = '较上周'
		} else if (value === '4') {
			dayShowTip.value = '较上月'
		}
		init()
	}
	const dateRangeChange = () => {
		if (!selfTime.value || !selfTime.value.length) {
			return
		}
		dayShowTip.value = '较上月'
		init()
	}
	const treeSelect = (value) => {
		searchForm.value.datastr = value[0]
	}
	const selfSearch = () => {
		selfChooseVisible.value = false
	}
	//销售报表弹窗
	const sketchVo = ref({})
	const salesKitRef = ref()
	const showPhoneCount = () => {
		salesKitRef.value.open()
	}

	/**
	 * ====================
	 *       销售助手
	 * ====================
	 */
	const salesHelper = ref({})
	const getSales = () => {
		const { personIds, tempPersonIds, ...other } = searchForm.value
		return dashboardApi.getSaleHelper(other)
	}
	/**
	 * ====================
	 *       合同金额图表
	 * ====================
	 */
	const useChartRef = ref()
	let usageChart
	const chartData = ref([])
	/**
	 * 绘制表格
	 */
	const drawUsageChart = () => {
		if (usageChart) {
			// usageChart.changeData(chartData.value)
			// return
			usageChart.destroy()
		}
		usageChart = new Chart({
			container: useChartRef.value,
			theme: 'classic',
			autoFit: true,
			height: 280,
			padding: 40
		})

		usageChart.data(chartData.value)

		usageChart
			.area()
			.encode('x', 'date')
			.encode('y', 'price')
			.style('fill', 'linear-gradient(-90deg, white 0%, #1890FF 100%)')
			.tooltip((d) => ({ name: '签约金额', value: `${d.totalPrice ?? 0}元` }))
			.tooltip((d) => ({ name: '订单量', value: `${d.num}个` }))

		usageChart
			.line()
			.encode('x', 'date')
			.encode('y', 'price')
			.style('stroke', '#1890FF')
			.style('strokeWidth', 2)
			.tooltip((d) => ({ name: '平均客单价', value: `${d.price}元` }))

		usageChart
			.axis({
				x: {
					title: '单位：日期',
					labelAutoHide: true,
					labelTransform: 'rotate(0)',
					labelFontSize: 12,
					labelAutoEllipsis: true

					// labelFormatter: (datum) => {
					// 	return dayjs(datum).format('MM-DD')
					// }
				},
				y: {
					title: '单位：元'
				}
			})
			.legend('color', { title: false, position: 'bottom' })

		usageChart.render()
	}
	/**
	 * 使用明细图表数据
	 * @param time 过滤时间
	 */
	const getChartsData = () => {
		const { personIds, tempPersonIds, ...other } = searchForm.value
		return dashboardApi.getBriefing(other)
	}

	/**
	 * ====================
	 *     客户转化
	 * ====================
	 */
	const customerFromId = ref()
	const customerTrans = ref({})
	const getCustomerTrans = () => {
		const { personIds, tempPersonIds, ...other } = searchForm.value
		const parmas = {
			customerFromId: customerFromId.value,
			...other
		}
		return dashboardApi.getCustomerTrans(parmas)
	}
	const onSourceChange = async () => {
		customerTrans.value = await getCustomerTrans()
	}
	/**
	 * 获取客户来源选项
	 */
	const customerFromOptions = ref([])
	customerSourceApi.list().then((res) => {
		res.unshift({ id: null, name: '所有来源' })
		customerFromOptions.value = res.map((item) => {
			return {
				value: item.id,
				label: item.name
			}
		})
		customerFromId.value = customerFromOptions.value[0].value
	})

	/**
	 * ====================
	 *     排行榜
	 * ====================
	 */
	const rankingList = ref([])
	const colorList = ['#FFF6D6', '#D6F1FF', '#E6EAEE']
	const getColor = (index) => {
		return 'background-color:' + colorList[index % 3] + ';border-radius: 34px;'
	}
	const getUnit = computed(() => {
		if (rankType.value === '0') return '(元)'
		if (['1', '2'].includes(rankType.value)) return '(个)'
		return ''
	})
	const rankType = ref('0')
	const getTankings = () => {
		const { personIds, tempPersonIds, ...other } = searchForm.value
		const parmas = {
			type: rankType.value,
			...other
		}
		return dashboardApi.getRankList(parmas)
	}

	const onRankChange = async () => {
		rankingList.value = await getTankings()
	}
</script>

<style lang="less" scoped>
	//导入字体样式
	@font-face {
		font-family: 'YSBTH';
		src: url('@/assets/fonts/YouSheBiaoTiHei-2.ttf');
	}

	.YSFont {
		font-family: 'YSBTH';
		font-weight: 400;
	}

	.dashboard-wrap {
		min-width: 1140px;
		padding: 0 10px 10px;
	}

	.updateTime {
		font-size: 18px;
		color: #999999;
		line-height: 1;
	}

	.trend-icon {
		width: 16px;
	}

	.section-title {
		position: relative;
		margin: 0 0 12px 0;
		padding-left: 18px;
		font-size: 24px;
		font-weight: 600;
		line-height: 1;
		.YSFont;
		&::after {
			content: '';
			position: absolute;
			left: 0;
			top: 20%;
			width: 5px;
			height: 60%;
			border-radius: 1px;
			background: var(--primary-7);
		}
	}

	.sale-title {
		margin-bottom: 24px;
		color: #666666;
		font-size: 18px;
		word-break: keep-all;
	}
	.sale-value {
		font-weight: 600;
		font-size: 28px;
		color: var(--primary-color);
		line-height: 1;
		transform: scaleY(1.1);
	}
	.sale-prop {
		font-weight: 700;
		font-size: 26px;
		line-height: 1;
		transform: scaleY(1.1);
	}

	.helper-title {
		color: #666666;
		font-size: 18px;
	}
	.helper-value {
		margin-top: 20px;
		font-weight: 600;
		font-size: 28px;
		color: var(--primary-color);
		transform: scaleY(1.1);
	}

	.transfer-wrap {
		margin-bottom: 24px;
		padding: 6px 50px 6px 17px;
		box-shadow: 0 10px 4px 0 rgba(68, 112, 255, 0.41);
		border-radius: 16px;
	}
	.transfer-icon {
		width: 38px;
	}
	.transfer-title {
		font-size: 18px;
	}
	.transfer-value {
		font-weight: 600;
		font-size: 18px;
	}

	.rank-wrap {
		padding: 14px 24px;
	}
	.rank-icon {
		width: 70px;
		top: -10px;
		left: 20px;
	}
	.rank-field {
		margin-left: 6px;
	}
	.rank-title {
		margin-left: 20px;
		font-size: 20px;
		font-weight: 500;
		color: #8b6c00;
	}
</style>
